package pers.cz.jefconfig.ext;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: JefConfig
 * @description: 扩展LinkedHashMap,增加二级缓存，支持特殊场景
 * @author: Cheng Zhi
 * @create: 2024-07-07 18:21
 **/
public class JefLinkedHashMap<K,V> extends LinkedHashMap<K,V> {

    private Map<String,Object> subCache;

    public JefLinkedHashMap() {
        super();
        // 初始化一个缓存，缓存大小设置为50
        subCache = new LinkedHashMap<String,Object>(){
            private static final long serialVersionUID = 2L;
            // 删除最老的值
            protected boolean removeEldestEntry(Map.Entry<String, Object> eldest) {
                return size()>50;
            }
        };
    }

    @Override
    public boolean containsKey(Object key) {

        boolean b = super.containsKey(key);
        if (b) {
            return b;
        }
        // 如果缓存中确实不存在这样的key, 需要再次判断二级缓存中是否存在
        return subCache.containsKey(key);
    }

    @Override
    public V get(Object key) {
        V o = super.get(key);
        // 如果key不是字符串，则没必要进行下一步
        if (!(key instanceof String) || o != null) {
            return o;
        }

        if (subCache.containsKey(key)) {
            return (V) subCache.get(key);
        }
        Map map = new LinkedHashMap();
        for (K k : this.keySet()) {
            if (k instanceof String && ((String) k).startsWith((String) key)) {
                V v = super.get(k);
                String newKey = ((String) k).substring(((String) key).length() + 1, ((String) k).length());
                map.put(newKey, v);
            }
        }
        if (map.size() != 0) {
            subCache.put((String) key, map);
        } else {
            subCache.put((String) key, null); // 防止缓存击穿
        }

        return (V) subCache.get(key);
    }
}
